﻿using System;
using System.Collections.Generic;
using Mono.Addins;
using IM.Interfaces;
using System.Windows.Forms;
using IM.DataTypes;
using Common.Interfaces;

namespace IM.Core.ExtensionNodes
{
    class MessageNode : ExtensionNode
    {
#pragma warning disable 0649

        [NodeAttribute("commandType", true)]
        string commandType;

#pragma warning restore 0649

        internal void MessageReceived(User user, string body)
        {
            try
            {
                if (!String.IsNullOrEmpty(this.commandType))
                {
					IUpdateCommand<ChatMessage> command = (IUpdateCommand<ChatMessage>)Addin.CreateInstance(commandType);
                    if (command != null)
                    {
                        ChatMessage message = new ChatMessage();
                        message.Sender = user;
                        message.Message = body;
                        message.Time = DateTime.Now;
                        command.Update(message);
                    }
                    else
                    {
                        Logging.Logger.AddError("The update command " + commandType + " not found!");
                    }
                }
                else
                {
                    Logging.Logger.AddError("The update command " + commandType + " is empty!");
                }
            }
            catch (Exception ex)
            {
                Logging.Logger.AddException(ex);
                // TODO consider throwing exception and let gui handle it
                MessageBox.Show(commandType + ": command exception. \n" + ex.ToString(), "Update Command exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
